package modelarts

import (
	"fmt"
	"log"
	"time"

	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

// 华为云的项目
type ProjectManager struct {
	EndPointUrlFormat string
	// 华为云的账户名
	HwAccountName string
	// 华为云的账户id
	HwAccountID string
	// Iam 账户名字
	IamName string
	// Iam 账户的密码
	IamPswd string
	// Iam 账户的access key
	IamAK string
	// Iam 账户的secret key
	IamSK string
	// obs 桶的根目录
	ObsBucketName string
	//ProjectMap 的字典。
	ProjectMap map[string]*ModelArtsProject
	// KUBE_CONFIG_PATH
	KubeConfigPath string
}

// 只获取羲和的项目
func (manager *ProjectManager) GetXiHeProject() (xiheProject *ModelArtsProject, err error) {
	// 区域为 cn-north-4 北京四，项目id为 0704467c7e8025362f1ec0019cc93707 的项目是羲和的
	return manager.GetProject("cn-north-4", "0704467c7e8025362f1ec0019cc93707")
}

// 根据区域和项目id获取项目
func (manager *ProjectManager) GetProject(region, projectid string) (project *ModelArtsProject, err error) {
	project = manager.ProjectMap[projectid]
	if project != nil {
		//如果在项目池中存在这个项目的对象，那么看看token是否过期，没过期就直接用。
		expireTime, _ := time.Parse(time.RFC3339Nano, project.Token.ExpiresAt)
		if expireTime.Before(time.Now()) {
			//如果已经过期了。 那么就重新生成一个token
			project.Token, project.TokenValue, err = GetToken(manager.IamAK, manager.IamSK, manager.IamName, manager.IamPswd, manager.HwAccountID, manager.HwAccountName, project.ProjectID, project.Region)
			if err != nil {
				log.Printf("项目[%s]的Token更新失败,error:%s", projectid, err.Error())
				return
			}
		}
		return
	}
	project = new(ModelArtsProject)
	project.ProjectID = projectid
	project.Region = region
	project.Manager = manager
	//----------- obs
	project.obsEndPointUrl = fmt.Sprintf("https://obs.%s.myhuaweicloud.com", project.Region)
	project.obsClient, err = obs.New(manager.IamAK, manager.IamSK, project.obsEndPointUrl)
	if err != nil {
		log.Printf("项目[%s]的obs初始化失败,error:%s", projectid, err.Error())
		return
	}
	project.EndPointUrl = fmt.Sprintf(manager.EndPointUrlFormat, project.Region, project.ProjectID)
	project.Token, project.TokenValue, err = GetToken(manager.IamAK, manager.IamSK, manager.IamName, manager.IamPswd, manager.HwAccountID, manager.HwAccountName, project.ProjectID, project.Region)
	if err != nil {
		log.Printf("项目[%s]的Token获取失败,error:%s", projectid, err.Error())
		return
	}
	manager.ProjectMap[projectid] = project
	return
}
